package com.hethongviet.vendingmobi;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.hethongviet.library.common.Utils;
import com.hethongviet.library.menu.Tab;
import com.hethongviet.library.menu.TabMenu;
import com.hethongviet.library.model.Transaction;
import com.hethongviet.library.msg.DialogMessageBack;
import com.hethongviet.library.network.ConstantNetwork.JSON;
import com.hethongviet.library.network.OnNetworkHandleListener;
import com.hethongviet.vendingmobi.helpers.Network;
import com.hethongviet.vendingmobi.model.Box;
import com.hethongviet.vendingmobi.model.Account;

import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import android.os.Bundle;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;

public class PageMainActivity extends OnNetworkHandleListener
{
	private final static int TAB_ACCOUNTS = 0;
	private final static int TAB_BOXES = TAB_ACCOUNTS + 1;
	private final static int TOTAL_TABS = TAB_BOXES + 1;

	private Button mButtonTabAccounts = null;
	private Button mButtonTabBoxes = null;
	private Button mButtonAddAccount = null;

	private ScrollView mLayoutTabAccounts = null;
	private LinearLayout mListAccounts = null;
	private ScrollView mLayoutTabBoxes = null;
	private LinearLayout mListBoxes = null;

	private EditText mEditTextAccountId = null;
	private Account mAccount = null;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		setContentView(R.layout.page_main);

		mButtonTabAccounts = (Button) findViewById(R.id.button_tab_accounts);
		mButtonTabBoxes = (Button) findViewById(R.id.button_tab_boxes);
		mLayoutTabAccounts = (ScrollView) findViewById(R.id.layout_tab_accounts);
		mListAccounts = (LinearLayout) findViewById(R.id.list_accounts);
		mLayoutTabBoxes = (ScrollView) findViewById(R.id.layout_tab_boxes);
		mListBoxes = (LinearLayout) findViewById(R.id.list_boxes);

		mButtonAddAccount = (Button) findViewById(R.id.button_add_account);
		mEditTextAccountId = (EditText) findViewById(R.id.text_account_id);

		mAccount = (Account) getIntent().getSerializableExtra(
				Constants.EXTRA_ACCOUNT);
		if (mAccount == null)
		{
			finish();
			return;
		}

		if (mAccount.getPermitAccess() == Account.PERMIT_CUSTOMER)
		{
			mButtonTabAccounts.setVisibility(View.GONE);
		}

		List<Box> boxsList = null;
		List<Account> accountsList = null;

		String jsonBoxInventoryString = getIntent().getStringExtra(
				Constants.EXTRA_BOX_INVENTORY);

		try
		{
			JSONArray jsonArray = new JSONArray(jsonBoxInventoryString);

			boxsList = new ArrayList<Box>();
			for (int i = 0; i < jsonArray.length(); i++)
			{
				JSONObject jsonObject = jsonArray.getJSONObject(i);

				Box box = new Box();
				try
				{
					box.setId(Integer.parseInt(jsonObject
							.getString(JSON.KEY_BOX_NUMBER)));
					box.setProductAmount(Integer.parseInt(jsonObject
							.getString(JSON.KEY_REMAIN_QUANTITY)));
				} catch (Exception e)
				{
					e.printStackTrace();
					continue;
				}
				box.setProductCode(jsonObject.getString(JSON.KEY_PRODUCT_CODE));

				boxsList.add(box);
			}
		} catch (JSONException e)
		{
			e.printStackTrace();

			finish();
			return;
		}

		/* Process for tab menu */
		Tab[] tabs = new Tab[TOTAL_TABS];

		tabs[TAB_ACCOUNTS] = new Tab();
		tabs[TAB_ACCOUNTS].setButton(mButtonTabAccounts);
		tabs[TAB_ACCOUNTS].setViewContain(mLayoutTabAccounts);

		tabs[TAB_BOXES] = new Tab();
		tabs[TAB_BOXES].setButton(mButtonTabBoxes);
		tabs[TAB_BOXES].setViewContain(mLayoutTabBoxes);

		new TabMenu(tabs, R.drawable.button_tab2,
				R.drawable.button_tab2_highlight);

		showListAccounts(accountsList);

		mButtonAddAccount.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
				String accountId = mEditTextAccountId.getText().toString();
				if (accountId == null || accountId.equals(""))
				{
					mEditTextAccountId.setText("");
					showDialogWithCatch(R.string.message_error_input_null);
					return;
				}

				if (accountId.length() < Constants.LENGTH_MIN_NUMBER)
				{
					showDialogWithCatch(R.string.message_error_input_too_short_number);
					return;
				}

				if (accountId.length() > Constants.LENGTH_MAX_NUMBER)
				{
					showDialogWithCatch(R.string.message_error_input_too_long_number);
					return;
				}

				for (int index = 0; index < accountId.length(); index++)
				{
					char c = accountId.charAt(index);

					if (!Character.isDigit(c))
					{
						showDialogWithCatch(R.string.message_error_wrong_input_number);
						return;
					}
				}

				Utils.showProgress(PageMainActivity.this,
						getString(R.string.please_wait));
				Network.sendRequestAddAccount(mAccount, accountId,
						Account.TYPE_BUYER);
			}
		});

		showListBoxes(boxsList);
	}

	@Override
	protected void onResume()
	{

		Network.setOnNetworkHandleListener(this);
		super.onResume();
	}

	private void showListAccounts(List<Account> accountsList)
	{
		mListAccounts.removeAllViews();

		if (accountsList == null)
		{
			Utils.debug("Account: There is not any account!");
			return;
		}

		final LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		for (Account account : accountsList)
		{
			final View view = layoutInflater.inflate(
					R.layout.layout_one_account, null);

			TextView textViewAccountId = (TextView) view
					.findViewById(R.id.layout_one_account_text);
			TextView textViewAccountRole = (TextView) view
					.findViewById(R.id.layout_one_account_role);

			textViewAccountId.setText(account.getCellPhone());
			textViewAccountRole.setText(account.getRole());

			mListAccounts.addView(view);
		}
	}

	private void showListBoxes(List<Box> boxesList)
	{
		mListBoxes.removeAllViews();

		if (boxesList == null)
		{
			Utils.debug("Box: There is not any box!");
			return;
		}

		final LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		View view = layoutInflater.inflate(R.layout.layout_one_box, null);

		TextView textViewBoxId = (TextView) view
				.findViewById(R.id.layout_one_box_id);

		TextView textViewBoxProductCode = (TextView) view
				.findViewById(R.id.layout_one_box_product_code);

		TextView textViewBoxProductQuality = (TextView) view
				.findViewById(R.id.layout_one_box_product_quantity);

		textViewBoxId.setText(getString(R.string.box_id));
		textViewBoxProductCode.setText(getString(R.string.box_product_code));
		textViewBoxProductQuality
				.setText(getString(R.string.box_product_quantity));

		textViewBoxId.setTextColor(Color.RED);
		textViewBoxProductCode.setTextColor(Color.RED);
		textViewBoxProductQuality.setTextColor(Color.RED);

		textViewBoxProductQuality.setTypeface(Typeface.DEFAULT_BOLD);

		mListBoxes.addView(view);

		for (Box box : boxesList)
		{
			view = layoutInflater.inflate(R.layout.layout_one_box, null);

			textViewBoxId = (TextView) view
					.findViewById(R.id.layout_one_box_id);

			textViewBoxProductCode = (TextView) view
					.findViewById(R.id.layout_one_box_product_code);

			textViewBoxProductQuality = (TextView) view
					.findViewById(R.id.layout_one_box_product_quantity);

			textViewBoxId.setText(box.getId() + "");
			textViewBoxProductCode.setText(box.getProductCode());
			textViewBoxProductQuality.setText(box.getProductAmount() + "");

			mListBoxes.addView(view);
		}
	}

	@Override
	public void onConnectFail(int typeError)
	{
		Utils.hideProgressDialog();
	}

	@Override
	public void onNetworkMessageIncomming(final Transaction transaction)
	{
		runOnUiThread(new Runnable()
		{
			@Override
			public void run()
			{

				if (transaction.getMethodSent().equals(Constants.ADD_ACCOUNT))
				{
					if (transaction.getMessageReceived().contains(
							Constants.RESULT_OK))
					{
						mEditTextAccountId.setText("");
						final LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

						final View view = layoutInflater.inflate(
								R.layout.layout_one_account, null);

						TextView textViewAccountId = (TextView) view
								.findViewById(R.id.layout_one_account_text);
						TextView textViewAccountRole = (TextView) view
								.findViewById(R.id.layout_one_account_role);

						textViewAccountId.setText(((Account) transaction
								.getModel()).getCellPhone());
						textViewAccountRole.setText(((Account) transaction
								.getModel()).getRole());

						mListAccounts.addView(view);

						showDialogWithCatch(R.string.message_success_add_account);
					}
					else
					// ERROR
					{
						/* ERROR: Account has been already created before */
						if (transaction.getMessageReceived()
								.contains("already"))
						{
							showDialogWithCatch(R.string.message_error_add_account_already);
						}
						else
						{
							showDialogWithCatch(R.string.message_error_add_account);
						}
					}
				}

				Utils.hideProgressDialog();
			}
		});
	}

	@Override
	protected Dialog onCreateDialog(int id)
	{
		if (id == R.string.message_error_input_too_long_number)
		{
			return new DialogMessageBack(this, true, String.format(
					getString(id), Constants.LENGTH_MAX_NUMBER), false);
		}
		else if (id == R.string.message_error_input_too_short_number)
		{
			return new DialogMessageBack(this, true, String.format(
					getString(id), Constants.LENGTH_MIN_NUMBER), false);
		}
		else if (id == R.string.message_success_add_account)
		{
			return new DialogMessageBack(this, false, id, false);
		}
		else
		{
			return createDialogStatusServer(id);
		}
	}
}
